const express = require("express");
const app = express();

const cors = require("cors");
const bodyParser = require("body-parser");
const expressJWT = require("express-jwt");

const config = require("./config.js");

app.use(cors());
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true,parameterLimit:50000}));

app.use(
	expressJWT({ secret: config.jwtSecretKey, algorithms: ["HS256"] }).unless({
		path: [/^\/api\//],
	})
);

const userRouter = require("./router/user");
const thingRouter = require("./router/thing");
const commentRouter = require("./router/comment");
const noticeRouter = require('./router/notice')
const adminRouter = require('./router/admin')

app.use("/api", userRouter);
app.use("/api", thingRouter);
app.use("/api", commentRouter);
app.use("/api", noticeRouter);
app.use("/api", adminRouter);

app.use((err, req, res, next) => {
	console.log(err.name);
	let errObj = null;
	switch (err.name) {
		case 'Browser Language Error':
			errObj = {
				code: 400,
				message: "客户端语法错误!",
			};
			break;
		case "UnauthorizedError":
			errObj = {
				code: 401,
				message: "身份认证失败!",
			};
			break;
		case "NotFound":
			errObj = {
				code: 404,
				message: "未找到资源!",
			};
			break;
		case "Forbiden":
			errObj = {
				code: 403,
				message: "禁止!",
			};
			break;
		case "Server Error":
			errObj = {
				code: 500,
				message: "服务器错误!",
			};
			break;
		case "Server Crash":
			errObj = {
				code: 503,
				message: "服务器当机!",
			};
			break;
	}
	res.send(errObj);
	next();
});

app.listen(3008, () => {
	console.log("api server running at http://127.0.0.1:3008");
});
